<template>
  <div class="batch-execution-view">
    <div class="toolbar">
      <div class="toolbar-left">
        <h3>批量执行管理</h3>
      </div>
      <div class="toolbar-right">
        <el-button type="primary" @click="showCreateBatchDialog">
          <el-icon><Plus /></el-icon>
          新建批量执行
        </el-button>
      </div>
    </div>

    <!-- 批量执行列表 -->
    <el-table
      v-loading="loading"
      :data="batches"
      stripe
      style="width: 100%"
    >
      <el-table-column prop="name" label="批量执行名称" width="200" />
      <el-table-column prop="description" label="描述" show-overflow-tooltip />
      
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column prop="total_scripts" label="总脚本数" width="100" />
      <el-table-column prop="completed_scripts" label="已完成" width="100" />
      <el-table-column prop="success_scripts" label="成功数" width="100" />
      <el-table-column prop="failed_scripts" label="失败数" width="100" />
      
      <el-table-column prop="duration" label="执行时长" width="120">
        <template #default="{ row }">
          {{ formatDuration(row.duration) }}
        </template>
      </el-table-column>
      
      <el-table-column prop="created_at" label="创建时间" width="150">
        <template #default="{ row }">
          {{ formatTime(row.created_at) }}
        </template>
      </el-table-column>
      
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="viewDetail(row)">查看详情</el-button>
          <el-button 
            v-if="row.status === 'pending'"
            size="small" 
            type="success" 
            @click="executeBatch(row)"
          >执行</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 创建批量执行对话框 -->
    <el-dialog
      v-model="createBatchVisible"
      title="新建批量执行"
      width="600px"
    >
      <el-form :model="batchForm" label-width="100px">
        <el-form-item label="执行名称" required>
          <el-input v-model="batchForm.name" placeholder="请输入批量执行名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="batchForm.description" type="textarea" placeholder="批量执行描述" />
        </el-form-item>
        <el-form-item label="选择脚本" required>
          <el-transfer
            v-model="batchForm.script_ids"
            :data="availableScripts"
            :titles="['可选脚本', '已选脚本']"
            :button-texts="['移除', '添加']"
            :format="{
              noChecked: '${total}',
              hasChecked: '${checked}/${total}'
            }"
            filterable
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createBatchVisible = false">取消</el-button>
          <el-button type="primary" @click="createBatch">创建</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { 
  getUiAutomationBatchExecutions,
  createUiAutomationBatchExecution 
} from '../../api/uiAutomation'

const props = defineProps({
  scripts: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['view-detail', 'execute-batch'])

// 响应式数据
const batches = ref([])
const loading = ref(false)
const createBatchVisible = ref(false)
const batchForm = reactive({
  name: '',
  description: '',
  script_ids: []
})

// 可选脚本列表
const availableScripts = computed(() => {
  return props.scripts.map(script => ({
    key: script.id,
    label: script.name,
    disabled: script.status !== 'active'
  }))
})

// 加载批量执行记录
const loadBatches = async () => {
  loading.value = true
  try {
    const response = await getUiAutomationBatchExecutions()
    if (response && response.data) {
      batches.value = Array.isArray(response.data.items) ? response.data.items : []
    }
  } catch (error) {
    ElMessage.error('加载批量执行记录失败')
  } finally {
    loading.value = false
  }
}

// 显示创建批量执行对话框
const showCreateBatchDialog = () => {
  batchForm.name = ''
  batchForm.description = ''
  batchForm.script_ids = []
  createBatchVisible.value = true
}

// 创建批量执行
const createBatch = async () => {
  if (!batchForm.name.trim()) {
    ElMessage.warning('请输入执行名称')
    return
  }
  
  if (batchForm.script_ids.length === 0) {
    ElMessage.warning('请选择要执行的脚本')
    return
  }
  
  try {
    await createUiAutomationBatchExecution(batchForm)
    ElMessage.success('批量执行创建成功')
    createBatchVisible.value = false
    loadBatches()
  } catch (error) {
    ElMessage.error('创建批量执行失败')
  }
}

// 查看详情
const viewDetail = (batch) => {
  emit('view-detail', batch)
}

// 执行批量任务
const executeBatch = (batch) => {
  emit('execute-batch', batch)
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    pending: 'info',
    running: 'warning',
    success: 'success',
    failed: 'danger',
    cancelled: 'info'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    pending: '待执行',
    running: '执行中',
    success: '成功',
    failed: '失败',
    cancelled: '已取消'
  }
  return texts[status] || status
}

// 格式化时长
const formatDuration = (duration) => {
  if (!duration) return '-'
  if (duration < 60) return `${duration}秒`
  const minutes = Math.floor(duration / 60)
  const seconds = duration % 60
  return `${minutes}分${seconds}秒`
}

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return '-'
  const date = new Date(timeStr)
  return date.toLocaleString('zh-CN')
}

onMounted(() => {
  loadBatches()
})
</script>

<style lang="scss" scoped>
.batch-execution-view {
  padding: 16px;
  
  .toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    
    .toolbar-left h3 {
      margin: 0;
      color: #303133;
    }
  }
}
</style>
